<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
  <meta content="yes" name="apple-mobile-web-app-capable">
  <meta content="yes" name="apple-touch-fullscreen">
  <meta content="telephone=no,email=no" name="format-detection">
  <title>业绩走势（带交易）</title>
  <link rel="stylesheet" href="../css/fund.css" />
  <style>
    canvas {
      height: 46.4vw;
    }
    .tooltip-title {
      line-height: 4vw;
    }
    @media only screen and (orientation: landscape) {
      .chart-card {
        margin: 0;
      }
      .chart-card-title {
        padding: 0 2.9985vw;
        width: 100%;
        height: 12vh;
        box-shadow: 0 1px 0 0 #E8E8E8;
        color: rgba(0, 0, 0, .85);
        font-size: 4.26667vh;
        line-height: 12vh;
        vertical-align: middle;
      }
      .chart-legend {
        position: relative;
        height: 6.667vh;
        padding: 0 2.9985vw;
        line-height: 6.667vh;
        flex-direction: row-reverse;
        box-shadow: 0 1px 0 0 #E8E8E8;
        font-size: 3.2vh;
      }
      .item {
        width: auto;
        margin-left: 1.7991004497751124vw;
      }
      .chart-legend-title {
        position: absolute;
        display: inline-block;
        left: 2.9985vw;
        color: #2e2e2e;
        top: 1px;
      }
      .tooltip-wrapper {
        height: 6.667vh;
        padding: 0 2.9985vw;
        line-height: 6.667vh;
      }
      .tooltip-content {
        font-size: 3.2vh;
        flex-direction: row-reverse;
      }
      .tooltip-title {
        position: absolute;
        display: inline-block;
        left: 2.9985vw;
        color: #2e2e2e;
        top: 1px;
        margin: 0;
        line-height: 6.667vh;
        font-size: 3.2vh;
      }

      #dealMoney {
        display: inline;
        width: auto;
      }
      canvas {
        width: 100%;
        height: 70.6667vh;
        display: block;
      }
      .chart-card-footer {
        width: 100%;
        height: 10.667vh;
        line-height: 10.667vh;
      }

      .item span.item-marker {
        width: 0.8995502248875562vw;
        height: 0.5333333333333333vh;
      }

      .item span.item-marker-point {
        width: 5px;
        height: 5px;
      }

      .item:nth-child(1) {
        order: 5;
      }
      .item:nth-child(2) {
        order: 4;
      }
      .item:nth-child(3) {
        order: 3;
      }
      .item:nth-child(4) {
        order: 2;
      }
      .item:nth-child(5) {
        order: 1;
      }

      .tab {
        height: 10.667vh;
        line-height: 10.667vh;
      }

      .tab .time-button {
        font-size: 3.4667vh;
        height: 10.667vh;
        line-height: 10.667vh;
      }
    }
  </style>
  <script src="../js/f2-all.min.js"></script>
  <script src="https://gw.alipayobjects.com/os/antv/assets/lib/jquery-3.2.1.min.js"></script>
  <script src="../js/util.js"></script>
</head>

<body>
  <div class="chart-card">
    <div class="chart-card-title">
      业绩走势
    </div>
    <!-- Content here -->
    <div class="chart-container">
      <div class="tooltip-wrapper">
        <div class="tooltip-title" id="tooltipTitle"></div>
        <div class="tooltip-content" id="tooltip">
          <div class="item">
            <span class="item-marker" style="background: #1890ff"></span>
            <span>本基金:</span>
            <span class="item-value" data-type="本基金">--</span>
          </div>
          <div class="item">
            <span class="item-marker" style="background: #5CDBD3"></span>
            <span>同类均值:</span>
            <span class="item-value" data-type="同类平均">--</span>
          </div>
          <div class="item" style="padding-right: 0;">
            <span class="item-marker" style="background: #B37FEB"></span>
            <span>沪深300:</span>
            <span class="item-value" data-type="沪深300">--</span>
          </div>
        </div>
      </div>
      <!-- 自定义 html 图表图例 -->
      <div class="chart-legend" id="chartLegend">
        <div class="chart-legend-title"></div>
        <div class="item">
          <span class="item-marker" style="background: #1890ff"></span>
          <span>本基金:</span>
          <span class="item-value" data-type="本基金">--</span>
        </div>
        <div class="item">
          <span class="item-marker" style="background: #5CDBD3"></span>
          <span>同类均值:</span>
          <span class="item-value" data-type="同类平均">--</span>
        </div>
        <div class="item" style="padding-right: 0;">
          <span class="item-marker" style="background: #B37FEB"></span>
          <span>沪深300:</span>
          <span class="item-value" data-type="沪深300">--</span>
        </div>
      </div>
      <!-- 图表主题 -->
      <canvas id="mountNode"></canvas>
      <!-- 时间切换 按钮 -->
      <div class="tab">
        <button class="time-button button-20 active" id="one-month">近 1 月</button>
        <button class="time-button button-20" id="three-month">近 3 月</button>
        <button class="time-button button-20" id="six-month">近 6 月</button>
        <button class="time-button button-20" id="one-year">近 1 年</button>
        <button class="time-button button-20" id="three-year">近 3 年</button>
      </div>
    </div>
  </div>
  <script>
      var Animate = F2.Animate;
      var Util = F2.Util;
      var Chart = F2.Chart;
      // 自定义线图变更动画
      Animate.registerAnimation('lineUpdate', function (updateShape, animateCfg) {
        var cacheShape = updateShape.get('cacheShape'); // 该动画 shape 的前一个状态
        var cacheAttrs = cacheShape.attrs; // 上一个 shape 属性

        var oldPoints = cacheAttrs.points; // 上一个状态的关键点
        var newPoints = updateShape.attr('points'); // 当前 shape 的关键点

        var oldLength = oldPoints.length;
        var newLength = newPoints.length;
        var deltaLength = oldLength - newLength;

        if (deltaLength > 0) {
          var firstPoint = newPoints[0];
          var lastPoint = newPoints[newPoints.length - 1];

          for (var i = 0; i < deltaLength; i++) {
            newPoints.splice(0, 0, firstPoint);
          }
        } else {
          deltaLength = Math.abs(deltaLength);
          var firstPoint1 = oldPoints[0];
          var lastPoint1 = oldPoints[oldPoints.length - 1];

          for (var k = 0; k < deltaLength; k++) {
            oldPoints.splice(0, 0, firstPoint1);
          }
          cacheAttrs.points = oldPoints;
        }
        updateShape.attr(cacheAttrs);
        updateShape.animate().to(Util.mix({
          attrs: {
            points: newPoints
          }
        }, animateCfg));
      });

      var colorMap = {
        '本基金': '#1890FF',
        '沪深300': 'rgba(92, 219, 211, 0.5)',
        '同类平均': 'rgba(179, 127, 235, 0.5)'
      };
      var sizeMap = {
        '本基金': 2,
        '沪深300': 1,
        '同类平均': 1
      };

      // 昨天的收益率，用于图例的绘制，无论时间切换维度多少，默认都会显示昨天的收益率
      var yesterdayRates = {
        '本基金': 14.12,
        '沪深300': 3.71,
        '同类平均': 3.54
      };
      var yesterday = '2018-05-22（昨日）';

      var landscape = window.innerWidth > window.innerHeight ? true : false;
      var xTickCount = landscape ? 5 : 3;

      // 图表绘制完成之后绘制图例
      $('#chartLegend .chart-legend-title').text(yesterday);
      $('#chartLegend .item-value').each(function(index, ele) {
        var type = $(ele).data('type');
        let value = yesterdayRates[type];
        let color;
        if (value > 0) {
          value = '+' + value;
          color = '#F5222D';
        }
        if (value < 0) {
          color = '#53BC20';
        }
        $(ele).css({
          color
        });
        $(ele).text(value + '%');
      });

      var chart = new Chart({
        id: 'mountNode',
        pixelRatio: window.devicePixelRatio,
        padding: [14, 'auto', 'auto']
      });
      var reportDateDef = {
        type: 'timeCat',
        tickCount: xTickCount,
        range: [ 0, 1 ],
        mask: 'YYYY-MM-DD'
      };
      // 处理数据
      $.getJSON('./data/performance/one-month.json', function(json) {
        chart.source(json, {
          rate: {
            tickCount: 5
          },
          name: {
            values: ['沪深300', '同类平均', '本基金']
          }
        });
        chart.scale('reportDate', reportDateDef);
        chart.animate({
          'axis-label': false
        });
        chart.axis('reportDate', {
          line: null,
          label: function(text, index, total) {
            var cfg = {
              textAlign: 'center'
            };
            if (index === 0) {
              cfg.textAlign = 'start';
            } else if (index === (total - 1)) {
              cfg.textAlign = 'end';
            }

            var arr = text.split('-');
            if (arr[0] === '2018') {
              cfg.text = arr[1] + '-' + arr[2];
            }
            return cfg;
          }
        });
        chart.axis('rate', {
          label: function(text) {
            text = text * 1;
            var cfg = {
              text: text.toFixed(2) + '%'
            };
            if (text > 0) {
              cfg.text = '+' + cfg.text;
            } else if (text === 0) {
              cfg.fill = '#000';
              cfg.fontWeight = 'bold';
            }
            return cfg;
          },
          grid: function(text, index) {
            if (text == 0) {
              return {
                lineDash: null
              };
            }
          }
        });
        chart.legend(false); // 不使用默认图例
        chart.tooltip({
          crosshairsStyle: {
            stroke: '#CAD7EF'
          },
          custom: true,
          onChange: function(obj) {
            var items = obj.items;
            var title = items[0].origin.reportDate;

            var rates = {};
            items.forEach(function(item) {
              rates[item.name] = item.value * 1;
            });
            $('#tooltipTitle').text(title);
            $('#tooltip .item-value').each(function(index, ele) {
              var type = $(ele).data('type');
              let value = rates[type];
              let color;
              if (value > 0) {
                value = '+' + value;
                color = '#F5222D';
              } else if (value < 0) {
                color = '#53BC20';
              } else {
                color = '#2E2E2E';
              }
              $(ele).css({
                color: color
              });
              $(ele).text(value + '%');
            });
            $('.tooltip-wrapper').css('visibility', 'visible');
          },
          onHide: function() {
            $('.tooltip-wrapper').css('visibility', 'hidden');
          }
        });
        chart.line()
          .position('reportDate*rate')
          .color('name', function(val) {
            return colorMap[val];
          })
          .size('name', function(val) {
            return sizeMap[val];
          })
          .animate({
            appear: {
              duration: 450,
            },
            update: {
              animation: 'lineUpdate',
              duration: 450
            }
          });
        chart.render();
      });

      // button 点击操作
      $('.tab button').click(function(e) {
        var target = $(e.target);
        var id = target.attr('id');
        if (target.hasClass('active')) {
          return;
        }

        var currentActive = $('.tab').find('button.active');
        currentActive.removeClass('active');
        target.addClass('active');

        var url = `./data/performance/${id}.json`;
        $.getJSON(url, function(json) {
          if (landscape) { // 横屏下的交互
            chart.tooltip(true);
            chart.scale('reportDate', reportDateDef);
            chart.clearInteraction(); // 先要将交互行为清楚
            if (id === 'one-year' || id === 'three-year') {
              chart.scrollBar({
                mode: 'x',
                xStyle: {
                  offsetY: -4
                }
              });
              chart
                .interaction('pan', {
                  mode: 'x',
                  preStart: function() {
                    chart.animate(false);
                  },
                  onEnd: function() {
                    chart.animate(true);
                  }
                })
                .interaction('pinch', {
                  mode: 'x',
                  preStart: function() {
                    chart.animate(false);
                  },
                  onEnd: function() {
                    chart.animate(true);
                  }
                });
            } else {
              chart.animate(true);
              chart.scrollBar(null);
            }
          }
          chart.changeData(json);
        });
      });
  </script>
</body>
</html>
